package model;

public class Distence {

	public static double similarity(String s1, String s2) {
		if (s1.length() < s2.length()) { // s1 should always be bigger
			String swap = s1;
			s1 = s2;
			s2 = swap;
		}
		int bigLen = s1.length();
		if (bigLen == 0) {
			return 1.0; /* both strings are zero length */
		}
		return (bigLen - computeEditDistance(s1, s2)) / (double) bigLen;
	}

	public static int computeEditDistance(String s1, String s2) {
		s1 = s1.toLowerCase();
		s2 = s2.toLowerCase();

		int[] costs = new int[s2.length() + 1];
		for (int i = 0; i <= s1.length(); i++) {
			int lastValue = i;
			for (int j = 0; j <= s2.length(); j++) {
				if (i == 0)
					costs[j] = j;
				else {
					if (j > 0) {
						int newValue = costs[j - 1];
						if (s1.charAt(i - 1) != s2.charAt(j - 1))
							newValue = Math.min(Math.min(newValue, lastValue),
									costs[j]) + 1;
						costs[j - 1] = lastValue;
						lastValue = newValue;
					}
				}
			}
			if (i > 0)
				costs[s2.length()] = lastValue;
		}
		return costs[s2.length()];
	}

	public static void main(String[] args) {
		double test1 = similarity(
				"In the name of Allah, Most Gracious, Most Merciful.",
				"In the name of Allah, most benevolent, ever-merciful.");
		double test2 = similarity("I am Junaid", "I am Junaid");
		double test3 = similarity(
				"ALL PRAISE BE to Allah, Lord of all the worlds,",
				"Praise be to Allah, the Cherisher and Sustainer of the worlds;");
		double test4 = similarity("Most Gracious, Most Merciful;",
				"Most beneficent, ever-merciful, ");
		double test5 = similarity(
				"But those who reject Faith and belie Our Signs, they shall be companions of the Fire; they shall abide therein.",
				"But those who deny and reject Our signs will belong to Hell , and there abide unchanged.");
		double test6 = similarity("he is Allah", "he is not Allah");
		System.out.println(test1);
		System.out.println(test2);
		System.out.println(test3);
		System.out.println(test4);
		System.out.println(test5);
		System.out.println(test6);
	}
}